package com.ymttest.business.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.security.PrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.apache.http.client.ClientProtocolException;

import com.ymatou.iapi.payment.parameter.*;
import com.ymatou.iapi.payment.service.*;
import com.ymatou.paygetway.parameter.*;
import com.ymatou.paygetway.serivce.*;
//import com.ymatou.paymentproxy.parameter.AcquireOrderBean;
//import com.ymatou.paymentproxy.parameter.AliPayNotifyBean;
//import com.ymatou.paymentproxy.parameter.AliPayWapCallBackBean;
//import com.ymatou.paymentproxy.parameter.AliPayWapNotifyBean;
//import com.ymatou.paymentproxy.parameter.FastRefundBean;
//import com.ymatou.paymentproxy.parameter.HbFq;
//import com.ymatou.paymentproxy.parameter.RefundNotifyBean;
//import com.ymatou.paymentproxy.parameter.SubmitRefundBean;
//import com.ymatou.paymentproxy.parameter.TradeDetail;
//import com.ymatou.paymentproxy.parameter.WeiXinNotifyBean;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.core.tool.RSAUtils;
import com.ymt.util.DataManager;
import com.ymttest.business.data.Sign;
import com.ymttest.business.data.applepaysign.ApplePayConstants;
import com.ymttest.business.data.applepaysign.Hex;
import com.ymttest.business.data.applepaysign.SecurityUtil;
import com.ymttest.common.enums.BankIdEnum;
import com.ymttest.database.model.MPayment;
import com.ymttest.database.model.MRefund;
//import com.ymttest.database.model.PPBussinessOrder;
//import com.ymttest.database.model.PPPayment;
//import com.ymttest.database.model.RefundRequest;
import com.ymttest.database.sqlwapper.JUserWapper;
import com.ymttest.database.sqlwapper.PayGateWayWapper;
//import com.ymttest.database.sqlwapper.PayGateWayWapper;
import com.ymttest.utils.BaofooSignature;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class PayGateWayCallService {
	/**
	 * 测试环境applepay商户号
	 */
//	public static String APPLEPAY_MERID_OLD = "308310053994237";
	public static String APPLEPAY_MERID = "310310153990887";
	public static String BaoFu_MERID = "1192439";
	public static String BaoFu_TerminalID = "36657";
	public static String WX_AppID="wx3b7bb547aea2ffa3";

	/**
	 * 初始化一个AcquireOrderBean 收单用
	 * 
	 * @return AcquireOrderBean
	 * @throws InterruptedException
	 */
	public static AcquireOrderBean initAcquireOrder(String type) throws InterruptedException {
		Logger.comment("初始化默认AcquireOrderBean,支付网关收单");
		String orderid = TestDataManager.getClientpaymentId();
		String payPrice = String.valueOf(new Random().nextInt(5) + 2);
		String productName = "自动化测试商品" + TestDataManager.randomStr(10);
		// Map m = new DefaultWapper().selectLastWeixinUser();
		String uid = new JUserWapper().selectWXUser().getUserId().toString();
		// String uid ="1";
		String ip = TestDataManager.getRandomIp();
		AcquireOrderBean acquireorderBean = new AcquireOrderBean();
		acquireorderBean.setAppId("AutoTest");
		acquireorderBean.setBankId(BankIdEnum.CMB.name());
		// 定金或者支付
		acquireorderBean.setBizCode("3");
		acquireorderBean.setCallbackUrl("http://www.ymatou.com/pay/result");
		acquireorderBean.setCurrency("CNY");
		acquireorderBean.setEncoding("65001");
		acquireorderBean.setExt("{\"SHOWMODE\":\"2\",\"PAYMETHOD\":\"2\", \"IsHangZhou\":1}");
		acquireorderBean.setNotifyUrl("http://mockforpay.iapi.ymatou.com/api/Trading/NotifyTradingEvent");
		acquireorderBean.setOrderId(orderid);
		acquireorderBean.setOrderTime(YMTDateUtil.getSysTime("yyyyMMddHHmmss"));
		acquireorderBean.setOriginAppId("AutoTest");
		acquireorderBean.setPayPrice(payPrice);
		acquireorderBean.setPayType(type);
		//新渠道
		if (type.equals("60")) {
			acquireorderBean.setPayType("61");
		}
		acquireorderBean.setProductName(productName);
		acquireorderBean.setSignMethod("MD5");
		if (type.equals("13")||type.equals("9")) {
			acquireorderBean.setSignMethod("RSA");
			if(type.equals("9")){
				acquireorderBean.setInstallmentNum(3);
			}
		}
		if(type.equals("70")){
			String sign = new Sign().signMd5(acquireorderBean, Sign.autoTestKey);
			acquireorderBean.setSign(sign);
		}
		acquireorderBean.setTraceId(TestDataManager.getRandomUUID().toString());
		acquireorderBean.setUserId(uid);
		acquireorderBean.setUserIp(ip);
		acquireorderBean.setVersion("1");
		acquireorderBean.setMemo("备注:" + TestDataManager.getRandomNum(3));
		return acquireorderBean;
	}

	/**
	 * 初始化Alipay bean 回调用
	 * 
	 * @param aqb
	 * @return
	 * @throws InterruptedException
	 */
	public static AliPayNotifyBean initAliPayNotifyBean(AcquireOrderBean aqb) throws InterruptedException {
		Logger.comment("初始化默认AliPayNotifyBean,支付网关阿里回调");
		AliPayNotifyBean alinotifyBean = new AliPayNotifyBean();
		alinotifyBean.setBody("自动化测试订单");
		alinotifyBean.setBusiness_scene("qrpay");
		alinotifyBean.setBuyer_email(TestDataManager.getEmail());
		alinotifyBean.setBuyer_id("2088" + TestDataManager.getRandomNum(10));
		alinotifyBean.setDiscount("-1");
		alinotifyBean.setExtra_common_param("自动化测试回传参数");
		alinotifyBean.setGmt_close(YMTDateUtil.getBeforeOrNextDay(1));
		alinotifyBean.setGmt_create(YMTDateUtil.getBeforeOrNextSecond(1));
		alinotifyBean.setGmt_payment(YMTDateUtil.getBeforeOrNextSecond(2));
		alinotifyBean.setGmt_refund(null);
		alinotifyBean.setIs_total_fee_adjust("N");
		alinotifyBean.setNotify_id(TestDataManager.getClientpaymentId());
		alinotifyBean.setNotify_time(YMTDateUtil.getBeforeOrNextSecond(3));
		alinotifyBean.setNotify_type("trade_status_sync");
		// trandno 是PaymentId
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		String trandno = ppm.getPaymentId();
		alinotifyBean.setOut_trade_no(trandno);
		alinotifyBean.setPayment_type("1");
		alinotifyBean.setPrice(aqb.getPayPrice());
		alinotifyBean.setQuantity("1");
		alinotifyBean.setRefund_status(null);
		alinotifyBean.setSeller_email("ap.ymt@ymatou.com");
		alinotifyBean.setSeller_id("2088701734809577");
		alinotifyBean.setSubject(aqb.getProductName());
		alinotifyBean.setTotal_fee(aqb.getPayPrice());
		alinotifyBean.setTrade_no(TestDataManager.getRandomUUID().toString());
		alinotifyBean.setTrade_status("TRADE_SUCCESS");
		alinotifyBean.setUse_coupon("N");
		//支付宝花呗分期回调标识
		if(aqb.getPayType().equals("9")){
			alinotifyBean.setOut_channel_type("PCREDIT_CC_PCREDIT_INSTALLMENT");
		}
		return alinotifyBean;
	}

	/**
	 * 
	 * @param aqb
	 *            收单对象
	 * @param discountAmount
	 *            优惠金额 目前是0
	 * @return
	 * @throws Exception
	 */
	public static CMBNotifyBean initCMBNotifyBean(AcquireOrderBean aqb, String discountAmount) throws Exception {
		Logger.comment("初始化默认initCMBNotifyBean,支付网关招商支付回调");
		CMBNotifyBean cmbNotifyBean = new CMBNotifyBean();
		cmbNotifyBean.setCharset("UTF-8");
		cmbNotifyBean.setSignType("RSA");
		cmbNotifyBean.setVersion("1.0");
		// NoticeData
		PNoticeData noticeData = new PNoticeData();
		noticeData.setAmount(aqb.getPayPrice());
		noticeData.setBankDate(YMTDateUtil.getSysTime("yyyyMMdd"));
		noticeData.setBankSerialNo(TestDataManager.getRandomUUID().toString());
		noticeData.setBranchNo("0021");
		noticeData.setDate(YMTDateUtil.getSysTime("yyyyMMdd"));
		noticeData.setDateTime(YMTDateUtil.getSysTime("yyyyMMddHHmmssSSS"));
		noticeData.setDiscountAmount(discountAmount);
		if (Double.valueOf(discountAmount) > 0) {
			noticeData.setDiscountFlag("Y");
		} else {
			noticeData.setDiscountFlag("N");
		}
		noticeData.setHttpMethod("POST");
		noticeData.setMerchantNo("000157");

		if (EnvSetup.getEnv().equals("uat")) {

			noticeData.setMerchantNo("006489");

		}
		noticeData.setMerchantPara("Pay");
		noticeData.setNoticeSerialNo(TestDataManager.getRandomUUID().toString());
		noticeData.setNoticeType("BKPAYRTN");
		noticeData.setNoticeUrl("noticeUrl");
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		String trandno = ppm.getPaymentId();
		noticeData.setOrderNo(trandno);
		cmbNotifyBean.setNoticeData(noticeData);

		return cmbNotifyBean;
	}

	/**
	 * ,支付网关招商签约回调
	 * 
	 * @param aqb
	 * @return
	 * @throws Exception
	 */
	public static CMBSignNotifyBean initCMBSignNotifyBean(AcquireOrderBean aqb) throws Exception {
		Logger.comment("初始化默认CMBSignNotifyBean,支付网关招商签约回调");
		CMBSignNotifyBean cmbSignNotifyBean = new CMBSignNotifyBean();
		cmbSignNotifyBean.setCharset("UTF-8");
		cmbSignNotifyBean.setSignType("RSA");
		cmbSignNotifyBean.setVersion("1.0");
		// NoticeData
		SNoticeData noticeData = new SNoticeData();
		noticeData.setBranchNo("0021");
		noticeData.setDateTime(YMTDateUtil.getSysTime("yyyyMMddHHmmss"));
		noticeData.setHttpMethod("POST");

		noticeData.setMerchantNo("000157");
		noticeData.setNoticeSerialNo(TestDataManager.getRandomUUID().toString());
		noticeData.setNoticeType("BKQY");
		noticeData.setNoticeUrl("noticeUrl");
		String agrNo = new PayGateWayWapper().selectCmbAggrementByUId(aqb.getUserId()).get(0).getId().toString();
		noticeData.setAgrNo(agrNo);
		noticeData.setUserID(aqb.getUserId());
		noticeData.setNoPwdPay("N");
		noticeData.setNoticePara("Sign");
		noticeData.setUserPidType("1");
		noticeData.setUserPidHash(String.valueOf(aqb.getUserId().hashCode()));
		noticeData.setRspCode("SUC0000");
		noticeData.setRspMsg("autotest");
		cmbSignNotifyBean.setNoticeData(noticeData);

		return cmbSignNotifyBean;
	}

	/**
	 * 招行回调报文加签
	 * 
	 * @param noticeData
	 * @return
	 * @throws Exception
	 */
	public static String SignCMBNoticeData(NoticeData noticeData) throws Exception {
		PrivateKey privateKey = RSAUtils.loadPrivateKey(EnvSetup.getData("privateK"));
		TreeMap tm = new TreeMap();
		Map m1 = (Map) (FormatUtil.GSONToObject(FormatUtil.beanToGSONString(noticeData), Map.class));
		// Logger.debug("noticeData to map:"+m1);
		tm.putAll(m1);
		String fromatS = FormatUtil.mapToHttpString(tm, false);
		Logger.debug("sign src:" + fromatS);
		String signSWR = RSAUtils.SignSHA1WithRSA(fromatS, privateKey);
		Logger.debug("SignSHA1WithRSA:" + signSWR);
		return signSWR;
	}

	/**
	 * 招行回调实际报文
	 * 
	 * @param cMBNotifyBean
	 * @return
	 */
	public static String CMBNoticeSendString(Object cmbNotifyBean) {
		String send = "jsonRequestData=";
		send += FormatUtil.urlEncode(FormatUtil.beanToGSONString(cmbNotifyBean));
		return send;
	}

	public static AliPayWapCallBackBean initAliPayCallBackBean(AcquireOrderBean aqb) throws InterruptedException {
		Logger.comment("初始化默认AliPayNotifyBean,支付网关阿里回调");
		AliPayWapCallBackBean alicbBean = new AliPayWapCallBackBean();
		// trandno 是PaymentId
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		String trandno = ppm.getPaymentId();
		alicbBean.setOut_trade_no(trandno);
		alicbBean.setRequest_token("request_token");
		alicbBean.setResult("success");
		alicbBean.setTrade_no(TestDataManager.getRandomUUID().toString());
		return alicbBean;
	}

	/**
	 * 收单接口
	 * 
	 * @param acquireorderBean
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static AcquireOrderCall acquireOrder(AcquireOrderBean acquireorderBean) throws ClientProtocolException, IOException {
		Logger.comment("调用支付收单");
		String sign = new Sign().signMd5(acquireorderBean, Sign.autoTestKey);
		acquireorderBean.setSign(sign);
		AcquireOrderCall acquireorderCall = new AcquireOrderCall();
		acquireorderCall.setData(false, acquireorderBean);
		if (acquireorderBean.getPayType().equals("14") || acquireorderBean.getPayType().equals("15") || acquireorderBean.getPayType().equals("16")) {
			acquireorderCall.addHeader("Mock", "1");
			String mockid = TestDataManager.getRandomUUID().toString();
			acquireorderCall.addHeader("MockId", mockid);
			acquireorderCall.addHeader("MockResult-WeiXin-return_code", "SUCCESS");
			acquireorderCall.addHeader("MockResult-WeiXin-result_code", "SUCCESS");
			if (acquireorderBean.getPayType().equals("16")) {
				String qr = "weixin://pay//bizpayurl?pr=UsZ4kmA";
				acquireorderCall.addHeader("MockResult-WeiXin-code_url", qr);
			}
			Logger.comment("调用支付收单MOCKID" + mockid);
		}if (acquireorderBean.getPayType().equals("70")) {
			//nothing
		}else{
			acquireorderCall.addHeader("Mock", "1");
			String mockid = TestDataManager.getRandomUUID().toString();
			acquireorderCall.addHeader("MockId", mockid);
			acquireorderCall.addHeader("MockResult-ApplePay-merId", PayGateWayCallService.APPLEPAY_MERID);
		}
		acquireorderCall.callService();
		Logger.comment("调用支付收单完成");
		return acquireorderCall;
	}

	/**
	 * 支付网关支付回调通知交易
	 * 
	 * @param type
	 * @param orderid
	 *            走第三方支付生成的交易号
	 * @param payprice
	 *            第三方支付金额
	 * @param userid
	 * @throws Exception
	 */
	public static void notifyCall(String type, String orderid, String payprice, int userid) throws Exception {
		Logger.comment("第三方异步支付回调交易");
		AcquireOrderBean aqb = initAcquireOrder(type);
		aqb.setOrderId(orderid);
		aqb.setPayPrice(payprice);
		aqb.setUserId(String.valueOf(userid));
		aqb.setProductName("接口自动化测试Test");
		// 根据第三方交易号，查询支付收单trackid
//		List<PPBussinessOrder> ppBussinessOrderList = new PayGateWayWapper().selectPPBussinessorderByOrderId(orderid);
//		aqb.setTraceId(ppBussinessOrderList.get(0).getTraceId());
		NotifyCall notifyCall = new NotifyCall(type);
		String send = "";
		if (type.equals("13")||type.equals("9")) {
			AliPayNotifyBean alinotifyBean = initAliPayNotifyBean(aqb);
			if(type.equals("9")){
				HbFq hb_fq_param=new HbFq();
				hb_fq_param.setHb_fq_num("3");
				hb_fq_param.setHb_fq_seller_percent("0");
				alinotifyBean.setHb_fq_param(hb_fq_param);
			}
			send = aliPayNotifyBeanToSend(alinotifyBean, aqb.getPayType());
		} else if (type.equals("14") || type.equals("15")|| type.equals("17")) {
			WeiXinNotifyBean wxnotifyBean = initWeixinBean(aqb);
			send = weiXinNotifyBeanToSend(wxnotifyBean);
		}
		// 招行
		else if (type.equals("50")) {
			CMBNotifyBean cmbNotifyBean = initCMBNotifyBean(aqb, "0");

			String sign = SignCMBNoticeData(cmbNotifyBean.getNoticeData());
			cmbNotifyBean.setSign(sign);
			send = PayGateWayCallService.CMBNoticeSendString(cmbNotifyBean);
		}
		// 宝付
		else if (type.equals("70")) {

			BaoFuNotifyBean baofu = PayGateWayCallService.initBaoFuNotifyBean(aqb);
			send = "data_content=" + new BaofooSignature().encryptData(FormatUtil.beanToGSONString(baofu));
		}

		notifyCall.setData(send);
		notifyCall.addHeader("Mock", "1");
		String mockid = TestDataManager.getRandomUUID().toString();
		notifyCall.addHeader("MockId", mockid);
		Logger.comment("添加Mock:" + mockid);
		notifyCall.callService();
	}

	/**
	 * 招商银行支付回调通知交易
	 * 
	 * @param type
	 * @param orderid
	 *            走第三方支付生成的交易号
	 * @param payprice
	 *            第三方支付金额
	 * @param userid
	 * @return 招商银行平台的补贴金额
	 * @throws Exception
	 */
	public static String cmbNotifyCall(String orderid, String payprice, int userid) throws Exception {
		Logger.comment("第三方异步支付回调交易");
		AcquireOrderBean aqb = initAcquireOrder("50");
		aqb.setOrderId(orderid);
		aqb.setPayPrice(payprice);
		aqb.setUserId(String.valueOf(userid));
		aqb.setProductName("接口自动化测试Test");
		// 根据第三方交易号，查询支付收单trackid
//		List<PPBussinessOrder> ppBussinessOrderList = new PayGateWayWapper().selectPPBussinessorderByOrderId(orderid);
//		aqb.setTraceId(ppBussinessOrderList.get(0).getTraceId());
		NotifyCall notifyCall = new NotifyCall("50");
		// 招商银行补贴金额随机
		String discountAmount = String.valueOf((new Random().nextInt(10)));
		// String discountAmount=String.valueOf((8));
		CMBNotifyBean cmbNotifyBean = initCMBNotifyBean(aqb, discountAmount);

		String sign = SignCMBNoticeData(cmbNotifyBean.getNoticeData());
		cmbNotifyBean.setSign(sign);
		String send = PayGateWayCallService.CMBNoticeSendString(cmbNotifyBean);

		notifyCall.setData(send);
		notifyCall.addHeader("Mock", "1");
		String mockid = TestDataManager.getRandomUUID().toString();
		notifyCall.addHeader("MockId", mockid);
		Logger.comment("添加Mock:" + mockid);
		notifyCall.callService();
		return discountAmount;
	}

	/**
	 * 支付网关退款回调通知交易
	 * 
	 * @param type
	 * @param orderid
	 * @param payprice
	 * @param userid
	 * @throws Exception
	 */
	public static void refundNotifyCall(String payType, String thirdTradingId, String payPrice, int userId) throws Exception {
		Logger.comment("第三方异步退款回调交易");
		AcquireOrderBean aqb = initAcquireOrder(payType);
		aqb.setOrderId(thirdTradingId);
		aqb.setPayPrice(payPrice);
		aqb.setUserId(String.valueOf(userId));
		aqb.setProductName("接口自动化测试Test");
		// 退款审核通过 根据第三方交易号，审核所有退款单
		approveRefundByTradeNo(thirdTradingId);
		// 审核通过后生成 RefundBatchNo
		// 查询申请退款的 RefundRequest 表
		List<MRefund> refundRequestList = new PayGateWayWapper().selectRefundRequestByTradeNo(thirdTradingId);

		for (MRefund refundRequest : refundRequestList) {
			// 退款审核通过后执行退款
			executeRefund(refundRequest, payType);

			String send = null;

			// 只有支付宝渠道才有退款通知，微信 没有
			if (payType.equals("10") || payType.equals("13")||payType.equals("9")) {
				// 构造通知bean数据
				RefundNotifyBean refundnotifyBean = initRefundNotifyBean(refundRequest);
				// 排序加签名
				String src = FormatUtil.beanToHttpString(refundnotifyBean, false);
				String sign = new Sign().SignSHA1WithRSA(src);
				refundnotifyBean.setSign(sign);
				refundnotifyBean.setSign_type("RSA");
				// 转换成最终发出的数据
				send = FormatUtil.beanToHttpString(refundnotifyBean, true);

			} else if (payType.equals("60")) {
				ApplePayRefundNotifyBean applerfb = initApplePayRefundNotifyBean(aqb);
				// 排序加签名
				send = ApplePayRefundNotifyToSend(applerfb, aqb);
				// 宝付支付的 退款回调
			} else if (payType.equals("70")) {

				send = FormatUtil.beanToGSONString(PayGateWayCallService.initBaoFuRefundNotifyBean(aqb));
				Logger.debug("baofuexecfund:" + send);

				send = "data_content=" + new BaofooSignature().encryptData(send);

			}

			// 转换成最终发出的数据
			RefundNotifyCall refundnotifyCall = new RefundNotifyCall();
			refundnotifyCall = new RefundNotifyCall(payType);
			refundnotifyCall.setData(send);
			refundnotifyCall.addHeader("Mock", "1");
			String mockid = TestDataManager.getRandomUUID().toString();
			refundnotifyCall.addHeader("MockId", mockid);
			refundnotifyCall.callService();
		}
	}

	/**
	 * 退款执行
	 * 
	 * @param refundRequest
	 * @param payType
	 */
	public static void executeRefund(MRefund refundRequest, String payType) {
		Logger.comment("执行退款执行");
		ExecuteRefundBean executerefundBean = new ExecuteRefundBean();
		ExecuteRefundCall executerefundCall = new ExecuteRefundCall();
		try {
			String refundbn = refundRequest.getRefundBatchNo();
			String refundid = refundRequest.getRefundId().toString();
			// 更新退款状态
			new PayGateWayWapper().updateRefundStatus(refundbn, "1");
			executerefundBean.setRefundId(refundid);
			executerefundCall.setData(executerefundBean);
			executerefundCall.addHeader("Mock", "1");
			// 13 为 app国际支付宝，15 微信
			String InstPaymentId=new PayGateWayWapper().selectPPPaymentByPaymentId(refundRequest.getPaymentId()).get(0).getInstitutionPaymentId();
			if (payType.equals("10") || payType.equals("13")||payType.equals("9")) {
				String mockResult = FormatUtil
						.urlEncode("is_success=T&result_details=" + refundbn + "^" +InstPaymentId + "^" + refundRequest.getRefundAmt().setScale(2) + "^SUCCESS");
				executerefundCall.addHeader("MockResult-AliPay-Result", mockResult);
			} else if (payType.equals("14") || payType.equals("15")) {
				executerefundCall.addHeader("MockResult-WeiXin-refund_status", "SUCCESS");
				executerefundCall.addHeader("MockResult-WeiXin-refund_fee", String.valueOf(refundRequest.getRefundAmt().setScale(2) .multiply(new BigDecimal(100)).intValue()));
			} else if (payType.equals("50")) {
				// 更新退款状态为 3
				new PayGateWayWapper().updateRefundStatus(refundbn, "3");
				// executerefundCall.addHeader("MockResult-Cmb-rspCode","SUC0000");
				// executerefundCall.addHeader("MockResult-Cmb-cardType","02");
				// executerefundCall.addHeader("MockResult-Cmb-orderAmount",refundRequest.getRefundAmount().toString());
				// executerefundCall.addHeader("MockResult-Cmb-discountAmount","0.00");
				// executerefundCall.addHeader("MockResult-Cmb-orderStatus","0");
				// executerefundCall.addHeader("MockResult-Cmb-date",YMTDateUtil.getSysTime("yyyyMMdd"));
				// executerefundCall.addHeader("MockResult-Cmb-orderNo",refundRequest.getPaymentId());
			}

			else if (payType.equals("70")) {
				// 更新退款状态为 3
				new PayGateWayWapper().updateRefundStatus(refundbn, "3");

			}

			String mockid = TestDataManager.getRandomUUID().toString();
			executerefundCall.addHeader("MockId", mockid);
			executerefundCall.callService();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 第三方异步回调支付
	 * 
	 * @param aqb
	 * @throws Exception
	 */
	public static void notifyCall(AcquireOrderBean aqb) throws Exception {
		Logger.comment("第三方异步回调支付");
		aqb.setProductName("接口自动化测试Test");
		NotifyCall notifyCall = new NotifyCall(aqb.getPayType());
		String send = "";
		if (aqb.getPayType().equals("10") || aqb.getPayType().equals("13")||aqb.getPayType().equals("9")) {
			AliPayNotifyBean alinotifyBean = initAliPayNotifyBean(aqb);
			send = aliPayNotifyBeanToSend(alinotifyBean, aqb.getPayType());
		} else if (aqb.getPayType().equals("14") || aqb.getPayType().equals("15") || aqb.getPayType().equals("16")|| aqb.getPayType().equals("17")) {
			WeiXinNotifyBean wxnotifyBean = initWeixinBean(aqb);
			send = weiXinNotifyBeanToSend(wxnotifyBean);
		} else if (aqb.getPayType().equals("11")) {
			AliPayWapNotifyBean aliwap = PayGateWayCallService.initAliPayWapNotify(aqb);
			send = PayGateWayCallService.signAliWapNotify(aliwap);
		} else if (aqb.getPayType().equals("60")||aqb.getPayType().equals("61")) {
			ApplePayNotifyBean apple = PayGateWayCallService.initApplePayNotifyBean(aqb);
			send = PayGateWayCallService.signApplePayNotify(apple);
		} else if (aqb.getPayType().equals("50")) {
			NotifyCall50 notifyCall50 = new NotifyCall50();
			CMBNotifyBean cmbNotifyBean = PayGateWayCallService.initCMBNotifyBean(aqb, "0");
			String sign = PayGateWayCallService.SignCMBNoticeData(cmbNotifyBean.getNoticeData());
			cmbNotifyBean.setSign(sign);
			send = PayGateWayCallService.CMBNoticeSendString(cmbNotifyBean);
			notifyCall50.setData(send);
			notifyCall50.addHeader("Mock", "1");
			String mockid = TestDataManager.getRandomUUID().toString();
			notifyCall50.addHeader("MockId", mockid);

			Logger.comment("添加Mock:" + mockid);
			notifyCall50.callService();
			return;
		} else if (aqb.getPayType().equals("70")) {
			BaoFuNotifyBean baofu = PayGateWayCallService.initBaoFuNotifyBean(aqb);
			send = "data_content=" + new BaofooSignature().encryptData(FormatUtil.beanToGSONString(baofu));
			NotifyCall70 notifyCall70 = new NotifyCall70();
			notifyCall70.setData(send);
			notifyCall70.addHeader("Mock", "1");
			String mockid = TestDataManager.getRandomUUID().toString();
			notifyCall70.addHeader("MockId", mockid);

			Logger.comment("添加Mock:" + mockid);
			notifyCall70.callService();
			return;
		}
		notifyCall.setData(send);
		notifyCall.addHeader("Mock", "1");
		String mockid = TestDataManager.getRandomUUID().toString();
		notifyCall.addHeader("MockId", mockid);
		Logger.comment("添加Mock:" + mockid);
		notifyCall.callService();
	}

	/**
	 * 招行专用支付回调 可以设置优惠金额
	 * 
	 * @param aqb
	 * @param discountAmonunt
	 * @throws Exception
	 */
	public static void notifyCall50(AcquireOrderBean aqb, String discountAmonunt) throws Exception {
		Logger.comment("第三方异步回调支付");
		aqb.setProductName("接口自动化测试Test");
		NotifyCall notifyCall = new NotifyCall(aqb.getPayType());
		String send = "";
		NotifyCall50 notifyCall50 = new NotifyCall50();
		CMBNotifyBean cmbNotifyBean = PayGateWayCallService.initCMBNotifyBean(aqb, discountAmonunt);
		String sign = PayGateWayCallService.SignCMBNoticeData(cmbNotifyBean.getNoticeData());
		cmbNotifyBean.setSign(sign);
		send = PayGateWayCallService.CMBNoticeSendString(cmbNotifyBean);
		notifyCall50.setData(send);
		notifyCall50.addHeader("Mock", "1");
		String mockid = TestDataManager.getRandomUUID().toString();
		notifyCall50.addHeader("MockId", mockid);

		Logger.comment("添加Mock:" + mockid);
		notifyCall50.callService();
	}

	/**
	 * 申请退款
	 * 
	 * @param aqb
	 * @return
	 * @throws Exception
	 */
	public static SubmitRefundBean submitRefund(AcquireOrderBean aqb) throws Exception {
		Logger.comment("申请退款");
		SubmitRefundBean submitrefundBean = new SubmitRefundBean();
		SubmitRefundCall submitrefundCall = new SubmitRefundCall();
		submitrefundBean.setAppId("AutoTest");
		submitrefundBean.setOrderId(TestDataManager.getRandomNum(12));
		submitrefundBean.setTraceId(TestDataManager.getRandomUUID().toString().replace("-", ""));
		List<TradeDetail> TradeDetails = new ArrayList<TradeDetail>();
		TradeDetail td = new TradeDetail();
		td.setTradeNo(aqb.getOrderId());
		td.setTradeType("2");
		TradeDetails.add(td);
		submitrefundBean.setTradeDetails(TradeDetails);
		String sign = new Sign().signMd5(submitrefundBean, Sign.autoTestKey);
		submitrefundBean.setSign(sign);
		submitrefundCall.setData(false, submitrefundBean);
		submitrefundCall.callService();
		return submitrefundBean;
	}

	/**
	 * 新版java版申请退款
	 * 
	 * @param aqb
	 * @return
	 * @throws Exception
	 */
	public static SubmitRefundBean JSubmitRefund(AcquireOrderBean aqb) throws Exception {
		Logger.comment("申请退款");
		SubmitRefundBean submitrefundBean = new SubmitRefundBean();
		com.ymatou.iapi.payment.service.SubmitRefundCall submitrefundCall = new com.ymatou.iapi.payment.service.SubmitRefundCall();
		submitrefundBean.setAppId("AutoTest");
		submitrefundBean.setOrderId(TestDataManager.getRandomNum(12));
		submitrefundBean.setTraceId(TestDataManager.getRandomUUID().toString().replace("-", ""));
		List<TradeDetail> TradeDetails = new ArrayList<TradeDetail>();
		TradeDetail td = new TradeDetail();
		td.setTradeNo(aqb.getOrderId());
		td.setTradeType("2");
		TradeDetails.add(td);
		submitrefundBean.setTradeDetails(TradeDetails);
		String sign = new Sign().signMd5(submitrefundBean, Sign.autoTestKey);
		submitrefundBean.setSign(sign);
		submitrefundCall.setData(false, submitrefundBean);
		submitrefundCall.callService();
		return submitrefundBean;
	}

	/**
	 * 申请部分退款
	 * 
	 * @param aqb
	 * @return
	 * @throws Exception
	 */
	public static AcquireRefundBean AcquireRefund(AcquireOrderBean aqb, String refundAmt) throws Exception {
		Logger.comment("申请部分退款");
		AcquireRefundBean acquirerefundBean = new AcquireRefundBean();
		AcquireRefundCall acquirerefundCall = new AcquireRefundCall();
		acquirerefundBean.setAppId("AutoTest");
		acquirerefundBean.setOrderId(TestDataManager.getClientpaymentId());
		acquirerefundBean.setRefundAmt(refundAmt);
		acquirerefundBean.setRefundNo(TestDataManager.getClientpaymentId());
		acquirerefundBean.setTradeNo(aqb.getOrderId());
		acquirerefundBean.setBizNo(TestDataManager.getRandomUUID().toString());
		acquirerefundBean.setTradeType(2);
		acquirerefundCall.setData(false, acquirerefundBean);
		acquirerefundCall.callService();
		return acquirerefundBean;
	}

	/**
	 * 审核退款
	 * 
	 * @param aqb
	 * @throws Exception
	 */
	public static void approveRefund(AcquireOrderBean aqb) throws Exception {
		Logger.comment("审核退款");
		com.ymatou.paymentproxy.parameter.ApproveRefundBean approverefundBean = new com.ymatou.paymentproxy.parameter.ApproveRefundBean();
		com.ymatou.paymentproxy.service.ApproveRefundCall approverefundCall = new com.ymatou.paymentproxy.service.ApproveRefundCall();
		String pid = PayGateWayCallService.getPaymentId(aqb);
		approverefundBean.setApproveUser("AutoTest");
		List<String> PaymentIds = new ArrayList<String>();
		PaymentIds.add(pid);
		approverefundBean.setPaymentIds(PaymentIds);
		approverefundCall.setData(false, approverefundBean);
		approverefundCall.callService();
	}

	/**
	 * 审核退款
	 * 
	 * @param tradeNo
	 *            第三方支付生成的交易号
	 * @throws Exception
	 */
	public static void approveRefundByTradeNo(String tradeNo) throws Exception {
		Logger.comment("审核退款");
		ApproveRefundBean approverefundBean = new ApproveRefundBean();
		ApproveRefundCall approverefundCall = new ApproveRefundCall();
		try {
			List<String> refundIdList = new ArrayList<String>();
			List<MRefund> refundRequestList = new PayGateWayWapper().selectRefundRequestByTradeNo(tradeNo);
			for (MRefund refundRequest : refundRequestList) {
				// 将所有该第三方支付交易下的退款，进行审核
				refundIdList.add(refundRequest.getRefundId().toString());
			}
			approverefundBean.setApproveUser("AutoTest");
			approverefundBean.setRefundIds(refundIdList);
			approverefundCall.setData(false, approverefundBean);
			approverefundCall.callService();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * java 审核退款
	 * 
	 * @param tradingid
	 * @param type
	 *            支付渠道
	 * @throws Exception
	 */

	public static void approveRefund(String tradingid) throws Exception {
		Logger.comment("审核退款");
		ApproveRefundCall approverefundCall = new ApproveRefundCall();
		com.ymatou.iapi.payment.parameter.ApproveRefundBean approverefundBean = new com.ymatou.iapi.payment.parameter.ApproveRefundBean();
		MRefund m = new PayGateWayWapper().selectRefundRequestByTradeNo(tradingid).get(0);
		String refundId = m.getRefundId().toString();
		approverefundBean.setApproveUser("AutoTest");
		List<String> refundIds = new ArrayList<String>();
		refundIds.add(refundId);
		approverefundBean.setRefundIds(refundIds);
		approverefundCall.setData(false, approverefundBean);
		approverefundCall.addDefHeader();
		approverefundCall.callService();
	}

	public static FastRefundBean fastRefund(AcquireOrderBean aqb) throws Exception {
		Logger.comment("快速退款");
		FastRefundBean fastrefundBean = new FastRefundBean();
		FastRefundCall fastrefundCall = new FastRefundCall();
		String pid = PayGateWayCallService.getPaymentId(aqb);
		fastrefundBean.setAppId("AutoTest");
		// 这个是支付那里的订单号 目前随便填写
		List<String> OrderIdList = new ArrayList<String>();
		OrderIdList.add(TestDataManager.getRandomNum(9));
		fastrefundBean.setOrderIdList(OrderIdList);
		fastrefundBean.setTraceId(TestDataManager.getRandomUUID().toString().replace("-", ""));
		fastrefundBean.setTradeType(1);
		fastrefundBean.setTradingId(aqb.getOrderId());
		fastrefundBean.setPaymentId(pid);
		fastrefundCall.setData(fastrefundBean);
		fastrefundCall.callService();
		return fastrefundBean;
	}

	/**
	 * AliPayNotifyBean加签并转换为SendString
	 * 
	 * @param alipaybean
	 * @return
	 * @throws Exception
	 */
	public static String aliPayNotifyBeanToSend(AliPayNotifyBean alipaybean, String type) throws Exception {
		Logger.comment("AliPayNotifyBean加签并转换为SendString");
		String send = null;
		if (type.equals("13")||type.equals("9")) {
			// 排序加签名
			String src = FormatUtil.beanToHttpString(alipaybean, false);
			String sign = Sign.SignSHA1WithRSA(src);
			alipaybean.setSign(sign);
			alipaybean.setSign_type("RSA");
			// 转换成最终发出的数据
			send = FormatUtil.beanToHttpString(alipaybean, true);
		} else {
			String src = FormatUtil.beanToHttpString(alipaybean, false);
			String sign = new Sign().signMd5(alipaybean, Sign.autoTestKey);
			alipaybean.setSign(sign);
			alipaybean.setSign_type("MD5");
			send = FormatUtil.beanToHttpString(alipaybean, true);
		}
		return send;
	}

	/**
	 * WeiXinNotifyBean加签并转换为SendString
	 * 
	 * @param weixinbean
	 * @return
	 * @throws Exception
	 */
	public static String weiXinNotifyBeanToSend(WeiXinNotifyBean weixinbean) throws Exception {
		Logger.comment("WeiXinNotifyBean加签并转换为SendString");
		// 排序加签名
		// String src = FormatUtil.beanToHttpString(weixinbean, false);
		// String sign = SignSHA1WithRSA(src);

		String sign = new Sign().signMd5(weixinbean, "&key=" + Sign.autoTestKey);
		weixinbean.setSign(sign);

		// 转换成最终发出的数据
		String send = FormatUtil.beanToXmlString(weixinbean);
		return send;
	}

	/**
	 * 初始化 WeiXinNotifyBean
	 * 
	 * @param aqb
	 * @return
	 * @throws InterruptedException
	 */
	public static WeiXinNotifyBean initWeixinBean(AcquireOrderBean aqb) throws InterruptedException {
		Logger.comment("初始化默认WeiXinNotifyBean,微信回调xml");
		// <xml><appid><![CDATA[wxf51a439c0416f182]]></appid>
		// <bank_type><![CDATA[CMB_DEBIT]]></bank_type>
		// <cash_fee><![CDATA[8200]]></cash_fee>
		// <fee_type><![CDATA[CNY]]></fee_type>
		// <is_subscribe><![CDATA[N]]></is_subscribe>
		// <mch_id><![CDATA[1234079001]]></mch_id>
		// <nonce_str><![CDATA[b82bbe0b28954973ad2a9c98618af516]]></nonce_str>
		// <openid><![CDATA[oASzYjrBI-LG8JMNSIC3c5VSynGU]]></openid>
		// <out_trade_no><![CDATA[20160412172258588000000000023844]]></out_trade_no>
		// <result_code><![CDATA[SUCCESS]]></result_code>
		// <return_code><![CDATA[SUCCESS]]></return_code>
		// <sign><![CDATA[E39042D497F3952F55F17D310B58EC36]]></sign>
		// <time_end><![CDATA[20160412172307]]></time_end>
		// <total_fee>8200</total_fee>
		// <trade_type><![CDATA[APP]]></trade_type>
		// <transaction_id><![CDATA[4009562001201604124771601467]]></transaction_id>
		// </xml>
		WeiXinNotifyBean wxnotifyBean = new WeiXinNotifyBean();
		wxnotifyBean.setAppid("wxf51a439c0416f182");
		if(aqb.getPayType().equals("17")){
			wxnotifyBean.setAppid(PaymentProxyCallService.WX_AppID);
		}
		wxnotifyBean.setAttach(TestDataManager.getRandomUUID().toString());
		wxnotifyBean.setBank_type(BankIdEnum.CMB.name());
		Double payprice = Double.valueOf(aqb.getPayPrice());
		int iprice = (int) (payprice * 100);
		Logger.debug("iprice:" + iprice);
		wxnotifyBean.setCash_fee(String.valueOf(iprice));
		wxnotifyBean.setCash_fee_type(null);
		wxnotifyBean.setCoupon_count("0");
		wxnotifyBean.setCoupon_fee("0");
		wxnotifyBean.setDevice_info(TestDataManager.getRandomUUID().toString());
		wxnotifyBean.setErr_code(null);
		wxnotifyBean.setErr_code_des(null);
		wxnotifyBean.setFee_type("CNY");
		wxnotifyBean.setIs_subscribe("N");
		if (aqb.getPayType().equals("14")) {
			wxnotifyBean.setMch_id("1278350701");
		} else if (aqb.getPayType().equals("16")) {
			wxnotifyBean.setMch_id("1278350701");
		}  else if (aqb.getPayType().equals("17")) {
			wxnotifyBean.setMch_id("1278350701");
		} else {
			wxnotifyBean.setMch_id("1234079001");
		}
		wxnotifyBean.setNonce_str(TestDataManager.getRandomUUID().toString().replace("-", "").substring(0, 31));
		// Map m = new DefaultWapper().selectLastWeixinUser();
		String uid = new JUserWapper().selectWXUser().getUserId().toString();
		String opid = new JUserWapper().selectWXUser().getOpenId();
		wxnotifyBean.setOpenid(opid);
		// wxnotifyBean.setOpenid("1234567");
		// trandno 是PaymentId
		// PPBussinessOrder ppb = new
		// PayGateWayWapper().selectPPBussinessorderByTraceId(aqb.getTraceId()).get(0);
		// 根据支付的第三方交易号，及表中的orderid 查询ppb
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		String trandno = ppm.getPaymentId();
		wxnotifyBean.setOut_trade_no(trandno);
		wxnotifyBean.setResult_code("SUCCESS");
		wxnotifyBean.setTime_end(YMTDateUtil.getSysTime("yyyyMMddHHmmss"));
		wxnotifyBean.setTotal_fee(String.valueOf(iprice));
		if (aqb.getPayType().equals("14")) {
			wxnotifyBean.setTrade_type("JSAPI");
		} else if (aqb.getPayType().equals("15")) {
			wxnotifyBean.setTrade_type("APP");
		} else {
			wxnotifyBean.setTrade_type("NATIVE");
		}
		wxnotifyBean.setTransaction_id(TestDataManager.getRandomUUID().toString().replace("-", "").substring(0, 31));
		wxnotifyBean.setReturn_code("SUCCESS");
		wxnotifyBean.setReturn_msg("成功");
		return wxnotifyBean;
	}

	/**
	 * 获取PaymentId
	 * 
	 * @param aqb
	 *            收单bean
	 * @return 对应的PaymentId
	 * @throws Exception
	 */
	public static String getPaymentId(AcquireOrderBean aqb) throws Exception {
		Logger.comment("通过AcquireOrderBean获取PaymentId");
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		String trandno = ppm.getPaymentId();
		return trandno;
	}

	/**
	 * 获取PPayment
	 * 
	 * @param aqb
	 *            收单bean
	 * @return 对应的PPayment
	 * @throws Exception
	 */
	public static MPayment getPPayment(AcquireOrderBean aqb) throws Exception {
		Logger.comment("通过AcquireOrderBean获取PPayment");
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		return ppm;
	}

	/**
	 * aliwap Notify加签
	 * 
	 * @param src
	 *            xml报文
	 * @return 全报文
	 */
	public static String signAliWapNotify(String src) {
		String tempsrc = "service=alipay.wap.trade.create.direct&v=1.0&sec_id=MD5&notify_data=" + src + Sign.autoTestKey;
		String md5 = TestDataManager.getMD5(tempsrc.getBytes());
		src = "service=alipay.wap.trade.create.direct&sign=" + md5 + "&v=1.0&sec_id=MD5&notify_data=" + FormatUtil.urlEncode(src);
		return src;
	}

	/**
	 * aliwap Notify加签
	 * 
	 * @param src
	 *            xml报文
	 * @return 全报文
	 */
	// TODO 需要改造 wap 走rsa校验
	public static String signAliWapNotify(AliPayWapNotifyBean aliwap) {
		String src = "<notify>" + FormatUtil.beanToNoRootXmlString(aliwap) + "</notify>";
		String tempsrc = "service=alipay.wap.trade.create.direct&v=1.0&sec_id=MD5&notify_data=" + src + Sign.autoTestKey;
		String md5 = TestDataManager.getMD5(tempsrc.getBytes());
		src = "service=alipay.wap.trade.create.direct&sign=" + md5 + "&v=1.0&sec_id=MD5&notify_data=" + FormatUtil.urlEncode(src);
		return src;
	}

	/**
	 * RSA
	 * 
	 * @param aliwap
	 * @return
	 * @throws Exception
	 */
	public static String signRSAAliWapNotify(AliPayWapNotifyBean aliwap) throws Exception {
		String src = "<notify>" + FormatUtil.beanToNoRootXmlString(aliwap) + "</notify>";
		String tempsrc = "service=alipay.wap.trade.create.direct&v=1.0&sec_id=0001&notify_data=" + src;
		String rsasign = FormatUtil.urlEncode(new Sign().SignSHA1WithRSA(tempsrc,false));
		byte[] rsabytes = RSAUtils.encryptByPublicKey(src.getBytes(), (RSAPublicKey) RSAUtils.loadPublicKey(EnvSetup.getData("publicK")));
		String base64src=Base64.getEncoder().encodeToString(rsabytes);
//		Logger.debug(RSAUtils.decryptByPrivateKey(base64src, (RSAPrivateKey) RSAUtils.loadPrivateKey(EnvSetup.getData("privateK"))));
		src = "service=alipay.wap.trade.create.direct&v=1.0&sec_id=0001&notify_data=" + FormatUtil.urlEncode(base64src)+"&sign=" + rsasign;
		return src;
	}

	/**
	 *  applepay Notify加签
	 * 
	 * @param 初始化过的ApplePayNotifyBean
	 * @return 全报文
	 */
	public static String signApplePayNotify(ApplePayNotifyBean applepay) throws Exception {
		// 转换成表单格式 不转码
		String plaintext = FormatUtil.beanToHttpString(applepay, false);
		// sha1加签
		byte[] signDigest = SecurityUtil.sha1(plaintext, ApplePayConstants.encoding);
		// 转换16进制
		signDigest = Hex.toHexBytes(signDigest, ApplePayConstants.encoding);
		PrivateKey privateKey = RSAUtils.loadPrivateKey(EnvSetup.getData("privateK"));
		// rsa加密
		byte[] signData = SecurityUtil.signWithSha1Rsa(privateKey, signDigest);
		// base64转码
		signData = Base64.getEncoder().encode(signData);
		applepay.setSignature(new String(signData));
		// 转换成表单格式 转码
		String send = FormatUtil.beanToHttpString(applepay, true);
		return send;
	}

	/**
	 * 初始化 AliPayWapNotifBean
	 * 
	 * @param aqb
	 * @return
	 * @throws InterruptedException
	 */
	public static AliPayWapNotifyBean initAliPayWapNotify(AcquireOrderBean aqb) throws InterruptedException {
		AliPayWapNotifyBean aliwap = new AliPayWapNotifyBean();
		aliwap.setBuyer_email(TestDataManager.getEmail());
		aliwap.setBuyer_id("2088" + TestDataManager.getRandomNum(10));
		aliwap.setGmt_create(YMTDateUtil.getBeforeOrNextSecond(1));
		aliwap.setGmt_payment(YMTDateUtil.getBeforeOrNextSecond(2));
		aliwap.setIs_total_fee_adjust("N");
		aliwap.setNotify_id(TestDataManager.getClientpaymentId());
		aliwap.setNotify_time(YMTDateUtil.getBeforeOrNextSecond(3));
		aliwap.setNotify_type("trade_status_sync");
		// trandno 是PaymentId
		// PPBussinessorder ppb = new
		// PayGateWayWapper().selectPPBussinessorderByTraceId(aqb.getTraceId()).get(0);
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		String trandno = ppm.getPaymentId();
		aliwap.setOut_trade_no(trandno);
		aliwap.setPayment_type("1");
		aliwap.setPrice(aqb.getPayPrice());
		aliwap.setQuantity("1");
		aliwap.setSeller_email("ap.ymt@ymatou.com");
		aliwap.setSeller_id("2088701734809577");
		aliwap.setSubject(aqb.getProductName());
		aliwap.setTotal_fee(aqb.getPayPrice());
		aliwap.setTrade_no(TestDataManager.getRandomUUID().toString());
		aliwap.setTrade_status("TRADE_SUCCESS");
		aliwap.setUse_coupon("N");
		return aliwap;
	}

	public static BaoFuRefundNotifyBean initBaoFuRefundNotifyBean(AcquireOrderBean aqb) throws InterruptedException {
		BaoFuRefundNotifyBean aprf = new BaoFuRefundNotifyBean();
		Integer price = new BigDecimal(aqb.getPayPrice()).multiply(new BigDecimal(100)).intValue();
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		MRefund RefundRequest = new PayGateWayWapper().selectRefundRequestByPaymentid(ppm.getPaymentId()).get(0);
		aprf.setMember_id(BaoFu_MERID);
		aprf.setRefund_amt(price.toString());
		aprf.setRefund_order_no(RefundRequest.getRefundBatchNo());
		aprf.setRefund_business_no(YMTDateUtil.getSysTime("yyyyMMddHHmmssSSS"));
		aprf.setResp_code("0000");
		aprf.setResp_msg("成功");
		return aprf;
	}

	/**
	 * 初始化退款回调
	 * 
	 * @param aqb
	 * @return
	 * @throws Exception
	 */
	private static RefundNotifyBean initRefundNotifyBean(AcquireOrderBean aqb) throws Exception {
		RefundNotifyBean refundnotifyBean = new RefundNotifyBean();
		RefundNotifyCall refundnotifyCall = new RefundNotifyCall();
		refundnotifyBean.setNotify_time(DataManager.getSysTime());
		refundnotifyBean.setNotify_type("batch_refund_notify");
		refundnotifyBean.setNotify_id(TestDataManager.getClientpaymentId());
		try {
			// 根据第三方支付返回的交易号查询第三方支付单号
			MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);

			 MRefund RefundRequest = new PayGateWayWapper().selectRefundRequestByPaymentid(ppm.getPaymentId()).get(0);
			String result_details = ppm.getInstitutionPaymentId() + "^" + aqb.getPayPrice() + "^SUCCESS" + "$ap.ymt@ymatou.com^2088701734809577^0.01^SUCCESS";
			refundnotifyBean.setResult_details(result_details);
			refundnotifyBean.setBatch_no(RefundRequest.getRefundBatchNo());
			refundnotifyBean.setSuccess_num("1");
		} catch (Exception e) {
			Logger.debug("" + e.getMessage());
		}
		return refundnotifyBean;
	}

	/**
	 * 初始化退款回调
	 * 
	 * @param RefundRequest
	 *            refundRequest 退款申请单
	 * @return
	 * @throws Exception
	 */
	private static RefundNotifyBean initRefundNotifyBean(MRefund refundRequest) throws Exception {
		RefundNotifyBean refundnotifyBean = new RefundNotifyBean();
		RefundNotifyCall refundnotifyCall = new RefundNotifyCall();
		refundnotifyBean.setNotify_time(DataManager.getSysTime());
		refundnotifyBean.setNotify_type("batch_refund_notify");
		refundnotifyBean.setNotify_id(TestDataManager.getClientpaymentId());
		String InstPaymentId=new PayGateWayWapper().selectPPPaymentByPaymentId(refundRequest.getPaymentId()).get(0).getInstitutionPaymentId();
		try {
			String result_details = InstPaymentId + "^" + refundRequest.getRefundAmt().setScale(2).toString() + "^SUCCESS" + "$ap.ymt@ymatou.com^2088701734809577^0.01^SUCCESS";
			refundnotifyBean.setResult_details(result_details);
			refundnotifyBean.setBatch_no(refundRequest.getRefundBatchNo());
			refundnotifyBean.setSuccess_num("1");
		} catch (Exception e) {
			Logger.debug("" + e.getMessage());
		}
		return refundnotifyBean;
	}

	/**
	 * 获取ali退款回调sendstring
	 * 
	 * @param refundNotifyBean
	 * @param aqb
	 * @return
	 * @throws Exception
	 */
	private static String aliPayRefundNotifyToSend(RefundNotifyBean refundNotifyBean, AcquireOrderBean aqb) throws Exception {
		Logger.comment("aliPayRefundNotify加签并转换为SendString");
		String send = null;
		if (aqb.getPayType().equals("13")||aqb.getPayType().equals("9")) {
			// 排序加签名
			String src = FormatUtil.beanToHttpString(refundNotifyBean, false);
			String sign = new Sign().SignSHA1WithRSA(src);
			refundNotifyBean.setSign(sign);
			refundNotifyBean.setSign_type("RSA");
			// 转换成最终发出的数据
			send = FormatUtil.beanToHttpString(refundNotifyBean, true);
		} else {
			String src = FormatUtil.beanToHttpString(refundNotifyBean, false);
			String sign = new Sign().signMd5(refundNotifyBean, Sign.autoTestKey);
			refundNotifyBean.setSign(sign);
			refundNotifyBean.setSign_type("MD5");
			send = FormatUtil.beanToHttpString(refundNotifyBean, true);
		}
		return send;
	}

	public static ApplePayNotifyBean initApplePayNotifyBean(AcquireOrderBean aqb) throws InterruptedException {
		ApplePayNotifyBean applyPayNotifyBean = new ApplePayNotifyBean();
		// trandno 是PaymentId
		// PPBussinessorder ppb = new
		// PayGateWayWapper().selectPPBussinessorderByTraceId(aqb.getTraceId()).get(0);
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		String trandno = ppm.getPaymentId();

		Integer price = Integer.valueOf((int) (Double.valueOf(aqb.getPayPrice()) * 100));

		applyPayNotifyBean.setBizType("000201");// 000201
		applyPayNotifyBean.setOrderId(trandno);// 17050410190438490

		applyPayNotifyBean.setTraceNo(TestDataManager.getRandomUUID().toString().replaceAll("-", ""));// 78591936

		applyPayNotifyBean.setSettleAmt(price);// 101

		applyPayNotifyBean.setSettleCurrencyCode("156");// 156
		applyPayNotifyBean.setTxnType("01");// 01+

		applyPayNotifyBean.setQueryId(TestDataManager.getRandomUUID().toString().replaceAll("-", ""));// 78591936

		applyPayNotifyBean.setAccessType("0");// 0
		applyPayNotifyBean.setTxnTime(YMTDateUtil.getSysTime("yyyyMMddHHmmss"));// 20170504101911
		applyPayNotifyBean.setPayCardType("01");// 01
		applyPayNotifyBean.setTxnSubType("01");// 01
		applyPayNotifyBean.setEncoding("UTF-8");// UTF-8
		applyPayNotifyBean.setVersion("5.0.0");// 5.0.0
		applyPayNotifyBean.setRespMsg("paysuccess");// paysuccess
		applyPayNotifyBean.setMerId(APPLEPAY_MERID);// 308310053994237
		applyPayNotifyBean.setCurrencyCode("156");// 156
		applyPayNotifyBean.setRespCode("00");// 00
		applyPayNotifyBean.setSignMethod("01");// 01

		applyPayNotifyBean.setTxnAmt(price);// 101
		return applyPayNotifyBean;
	}

	public static ApplePayRefundNotifyBean initApplePayRefundNotifyBean(AcquireOrderBean aqb) throws InterruptedException {
		ApplePayRefundNotifyBean aprf = new ApplePayRefundNotifyBean();
		Integer price = new BigDecimal(aqb.getPayPrice()).multiply(new BigDecimal(100)).intValue();
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		MRefund RefundRequest = new PayGateWayWapper().selectRefundRequestByPaymentid(ppm.getPaymentId()).get(0);
		aprf.setCurrencyCode("156");
		aprf.setMerId(PayGateWayCallService.APPLEPAY_MERID);
		aprf.setOrderId(RefundRequest.getRefundBatchNo());
		aprf.setRespCode("00");
		aprf.setTxnAmt(price.toString());
		return aprf;
	}

	public static String ApplePayRefundNotifyToSend(ApplePayRefundNotifyBean applerfb, AcquireOrderBean aqb) throws Exception {
		String plaintext = FormatUtil.beanToHttpString(applerfb, false);
		byte[] signDigest = SecurityUtil.sha1(plaintext, ApplePayConstants.encoding);
		signDigest = Hex.toHexBytes(signDigest, ApplePayConstants.encoding);
		PrivateKey privateKey = RSAUtils.loadPrivateKey(EnvSetup.getData("privateK"));
		byte[] signData = SecurityUtil.signWithSha1Rsa(privateKey, signDigest);
		signData = Base64.getEncoder().encode(signData);
		applerfb.setSignature(new String(signData));
		String send = FormatUtil.beanToHttpString(applerfb, true);
		return send;
	}

	/**
	 * 宝付Notify
	 * 
	 * @param aqb
	 * @return
	 * @throws InterruptedException
	 */
	public static BaoFuNotifyBean initBaoFuNotifyBean(AcquireOrderBean aqb) throws InterruptedException {
		BaoFuNotifyBean baoFuNotifyBean = new BaoFuNotifyBean();

		// trandno 是PaymentId
		// PPBussinessorder ppb = new
		// PayGateWayWapper().selectPPBussinessorderByTraceId(aqb.getTraceId()).get(0);
		MPayment ppm = new PayGateWayWapper().selectPaymentByTradingid(aqb.getOrderId()).get(0);
		String trandno = ppm.getPaymentId();

		// setBuyer_email
		baoFuNotifyBean.setAccount_no(TestDataManager.getEmail());
		baoFuNotifyBean.setAdditional_info("");
		baoFuNotifyBean.setBank_voucher_no(TestDataManager.getRandomUUID().toString());
		// setBuyer_id
		baoFuNotifyBean.setBuyer_id("2088" + TestDataManager.getRandomNum(10));
		baoFuNotifyBean.setData_type("json");
		// 宝付商户号
		baoFuNotifyBean.setMember_id("1192439");
		// 1：借记卡 2：贷记卡 3：其 他（余额）
		baoFuNotifyBean.setPay_type("1");
		baoFuNotifyBean.setReq_reserved("");
		// 0000代表成功
		baoFuNotifyBean.setResp_code("0000");
		baoFuNotifyBean.setResp_msg("交易成功");
		// 分为单位
		Integer price = new BigDecimal(aqb.getPayPrice()).multiply(new BigDecimal(100)).intValue();
		baoFuNotifyBean.setSucc_amt(price.toString());
		// 宝付终端号branchNo
		baoFuNotifyBean.setTerminal_id("36657");
		baoFuNotifyBean.setTrade_date(YMTDateUtil.getSysTime("yyyyMMddHHmmss"));
		baoFuNotifyBean.setTrans_id(trandno);
		baoFuNotifyBean.setTxn_sub_type("08");
		baoFuNotifyBean.setTxn_type("20199");
		baoFuNotifyBean.setVersion("4.0.0.0");
		baoFuNotifyBean.setVoucher_no(TestDataManager.getRandomUUID().toString().replaceAll("-", ""));
		baoFuNotifyBean.setOrder_id(TestDataManager.getRandomUUID().toString());
		// alinotifyBean.setBody("自动化测试订单");
		// alinotifyBean.setBusiness_scene("qrpay");
		// alinotifyBean.setBuyer_email(TestDataManager.getEmail());
		// alinotifyBean.setBuyer_id("2088" + TestDataManager.getRandomNum(10));
		// alinotifyBean.setDiscount("0");
		// alinotifyBean.setExtra_common_param("自动化测试回传参数");
		// alinotifyBean.setGmt_close(YMTDateUtil.getBeforeOrNextDay(1));
		// alinotifyBean.setGmt_create(YMTDateUtil.getBeforeOrNextSecond(1));
		// alinotifyBean.setGmt_payment(YMTDateUtil.getBeforeOrNextSecond(2));
		// alinotifyBean.setGmt_refund(null);
		// alinotifyBean.setIs_total_fee_adjust("N");
		// alinotifyBean.setNotify_id(TestDataManager.getClientpaymentId());
		// alinotifyBean.setNotify_time(YMTDateUtil.getBeforeOrNextSecond(3));
		// alinotifyBean.setNotify_type("trade_status_sync");
		// // trandno 是PaymentId
		// // PPBussinessorder ppb = new
		// //
		// PayGateWayWapper().selectPPBussinessorderByTraceId(aqb.getTraceId()).get(0);
		// PPBussinessOrder ppb = new
		// PayGateWayWapper().selectPPBussinessorderByOrderId(aqb.getOrderId()).get(0);
		// String businessoid = ppb.getBussinessOrderId();
		// PPPayment ppm = new
		// PayGateWayWapper().selectPPPaymentByBussinessOrderId(businessoid).get(0);
		// String trandno = ppm.getPaymentId();
		// alinotifyBean.setOut_trade_no(trandno);
		// alinotifyBean.setPayment_type("1");
		// alinotifyBean.setPrice(aqb.getPayPrice());
		// alinotifyBean.setQuantity("1");
		// alinotifyBean.setRefund_status(null);
		// alinotifyBean.setSeller_email("ap.ymt@ymatou.com");
		// alinotifyBean.setSeller_id("2088701734809577");
		// alinotifyBean.setSubject(aqb.getProductName());
		// alinotifyBean.setTotal_fee(aqb.getPayPrice());
		// alinotifyBean.setTrade_no(TestDataManager.getRandomUUID().toString());
		// alinotifyBean.setTrade_status("TRADE_SUCCESS");
		// alinotifyBean.setUse_coupon("N");
		return baoFuNotifyBean;
	}
}
